<template>
    <div class="vue-body">
        <!-- 搜索条件, 按钮 放在一行 -->
        <div class="btn-header">
            <!-- 搜索条件 -->
            <div>
                <el-input style="width: 200px; margin-right: 5px;" placeholder="请输入用户名" suffix-icon="el-icon-search"
                          v-model="params.name"></el-input>
                <el-input style="width: 200px; margin-right: 5px;" placeholder="请输入昵称" suffix-icon="el-icon-position"
                          v-model="params.nickname"></el-input>
                <el-input style="width: 200px; margin-right: 5px;" placeholder="请输入角色" suffix-icon="el-icon-message"
                          v-model="params.name"></el-input>
                <el-button type="primary" @click="load">搜索</el-button>
            </div>
            
            <!-- 操作按钮 -->
            <div class="btn-inner-div">
                <el-button type="primary" @click="add">新增 <i class="el-icon-circle-plus-outline"></i></el-button>
                <el-button type="danger">批量删除 <i class="el-icon-remove-outline"></i></el-button>
                <el-button type="primary">导入 <i class="el-icon-bottom"></i></el-button>
                <el-button type="primary">导出 <i class="el-icon-top"></i></el-button>
            </div>
        </div>
        
        <!-- 列表查询 -->
        <el-table :data="tableData" border stripe :header-cell-class-name="headerBg" v-loading="loading">
            <el-table-column prop="id" label="ID" width="80" sortable align="center"></el-table-column>
            <el-table-column prop="title" label="公告标题" width="140" align="center"></el-table-column>
            <el-table-column prop="content" label="公告详情" width="300" align="left">
                <template slot-scope="scope">
                    <el-tooltip
                         :content="scope.row.content"
                         placement="bottom"
                         raw-content
                         popper-class="tip-class"
                         v-if="scope.row.content"
                    >
                        <span v-if="scope.row.content && scope.row.content.length <= 70">{{ scope.row.content }}</span>
                        <span v-if="scope.row.content && scope.row.content.length > 70">{{
                                scope.row.content.substr(0, 70) + "..."
                            }}</span>
                    </el-tooltip>
                    <span v-else-if="scope.row.content== null"> NA </span>
                </template>
            </el-table-column>
            <el-table-column prop="redirectUrl" label="跳转连接" width="200" align="center"></el-table-column>
            <el-table-column prop="status" label="发布状态" width="80" align="center"></el-table-column>
            <el-table-column prop="publishTime" label="发布时间" width="100" align="center"></el-table-column>
            <el-table-column prop="pageView" label="浏览量" width="80" align="center"></el-table-column>
            <el-table-column prop="createUser" label="创建用户" width="200" align="center"></el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="200" sortable align="center"
                             :formatter="formatDate"></el-table-column>
            <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                    <el-button type="success" size="mini" @click="handleDetail(scope.row)">详情 <i
                         class="el-icon-zoom-in"></i></el-button>
                    <el-button type="success" size="mini">编辑 <i class="el-icon-edit"></i></el-button>
                    <el-button type="danger" size="mini">删除 <i class="el-icon-remove-outline"></i></el-button>
                </template>
            </el-table-column>
        </el-table>
        
        <!-- 分页查询 -->
        <div style="padding: 10px 0; text-align: left;">
            <el-pagination
                 @size-change="handleSizeChange"
                 @current-change="handleCurrentChange"
                 :current-page="pageNum"
                 :page-sizes="[5, 10, 20, 50]"
                 :page-size="pageSize"
                 layout="total, sizes, prev, pager, next, -> , jumper"
                 :total="total">
            </el-pagination>
        </div>
        
        <!-- 添加公告信息 -->
        <el-dialog top="12vh" title="添加公告信息"
                   :visible.sync="dialogFormVisible"
                   append-to-body
                   :close-on-click-modal=true
                   width="34%"
        >
            
            <div class="notice-title">
                <label class="el-form-item__label" style="width: 100px;"><span style="color: red">* </span>文章标题：
                </label>
                <el-input prefix-icon="el-icon-document" style="width: 85%" placeholder="请输入公告标题"
                          v-model="title"></el-input>
            </div>
            <div style="height: 400px; overflow: auto">
                <quill-editor
                     ref="myQuillEditor"
                     v-model="content"
                     :options="editorOption"
                     @blur="onEditorBlur($event)"
                     @focus="onEditorFocus($event)"
                     @change="onEditorChange($event)"
                     style="height: 334px"
                />
            </div>
            <template #footer>
                  <span class="dialog-footer align-footer">
                        <el-button @click="dialogFormVisible = false">取 消</el-button>
                        <el-button type="primary" @click="submit">确 定</el-button>
                  </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import {page, saveNotice} from "@/api/notice/notice"
import dayjs from "dayjs";

// 引入富文本quill-editor相关组件依赖
import {quillEditor, Quill} from 'vue-quill-editor'
import {quillRedefine} from 'vue-quill-editor-upload'
import {container, QuillWatch} from 'quill-image-extend-module'
import ImageResize from 'quill-image-resize-module' // 引用，调整图片大小
Quill.register('modules/imageResize', ImageResize)

import {ImageDrop} from 'quill-image-drop-module' // 引用，粘贴图片
Quill.register('modules/imageDrop', ImageDrop) //粘贴图片

export default {
    name: "pending",
    des: "待发布公告",
    data() {
        return {
            loading: false, // 列表等待转圈
            tableData: [],
            total: 10,
            pageNum: 1,
            pageSize: 10,
            headerBg: 'headerBg',
            dialogFormVisible: false, // 用户新增弹窗状态
            
            params: {}, // 查询条件
            dialogFormDetail: false, // 用户详情弹窗状态
            percent: 0,
            showProgress: false,
            
            // 文本编辑器
            content: "",
            title: "标题",
            id: "",
            
            editorOption: {},  // 必须初始化为对象 init  to Object
        }
    },
    created() {
        this.load()
        
        this.editorOption = quillRedefine({
            modules: {
                toolbar: [
                    ["bold", "italic", "underline", "strike"], //加粗，斜体，下划线，删除线
                    ["blockquote", "code-block"], //引用，代码块
                    [{header: 1}, {header: 2}], // 标题，键值对的形式；1、2表示字体大小
                    [{list: "ordered"}, {list: "bullet"}], //列表
                    [{script: "sub"}, {script: "super"}], // 上下标
                    [{indent: "-1"}, {indent: "+1"}], // 缩进
                    [{direction: "rtl"}], // 文本方向
                    [{size: ["small", false, "large", "huge"]}], // 字体大小
                    [{header: [1, 2, 3, 4, 5, 6, false]}], //几级标题
                    [{color: []}, {background: []}], // 字体颜色，字体背景颜色
                    [{font: []}], //字体
                    [{align: []}], //对齐方式
                    ["clean"], //清除字体样式
                    ["image", "video"], //上传图片、上传视频
                ],
                
                // 调整图片大小
                imageResize: {
                    displayStyles: {
                        backgroundColor: 'black',
                        border: 'none',
                        color: 'white'
                    },
                    modules: ['Resize', 'DisplaySize', 'Toolbar']
                },
                
                imageDrop: true,  // 图片粘贴
            },
            
            // 图片上传的设置
            uploadConfig: {
                action: this.API.basePath + '/api/notice/upload',  // 必填参数 图片上传地址,这里的后台是node
                too: [['bold', 'italic', 'underline', 'strike'], ['blockquote', 'code-block'], [{'header': 1}, {'header': 2}], [{'list': 'ordered'}, {'list': 'bullet'}], [{'script': 'sub'}, {'script': 'super'}], [{'indent': '-1'}, {'indent': '+1'}], [{'direction': 'rtl'}], [{'size': ['small', false, 'large', 'huge']}], [{'header': [1, 2, 3, 4, 5, 6, false]}], [{'color': []}, {'background': []}], [{'font': []}], [{'align': []}], ['clean'], ['image']],
                header: (xhr) => {
                    //关键是这句话
                    xhr.setRequestHeader(this.API.tokenKey, sessionStorage.getItem("manage-token"));
                    return xhr
                },
                res: (response) => {
                    return response.msg; // return图片url
                },
                accept: 'image/png, image/gif, image/jpeg, image/bmp, image/x-icon',
                name: 'file'  // 图片上传参数名
            },
            theme: 'snow', // 这个是组题
        })
    },
    methods: {
        handleSizeChange(pageSize) {
            console.log(pageSize)
            this.pageSize = pageSize;
            this.load()
        },
        handleCurrentChange(pageNum) {
            console.log(pageNum)
            this.pageNum = pageNum
            this.load()
        },
        load() {
            this.loading = true
            page(this.pageNum, this.pageSize, this.params).then(res => {
                this.loading = false
                this.tableData = res.data.records;
                this.total = res.data.total;
            }).catch(() => this.loading = false)
        },
        changSwitch(row) { // 开关
        
        },
        add() { // 新增用户按钮
            this.dialogFormVisible = true
            this.id = ''
        },
        
        // 新增、修改弹窗提交
        submit() {
            debugger
            if (this.title === '') {
                this.$message({
                    type: "error",
                    message: '标题为空！'
                })
                return
            }
            
            if (this.content === '') {
                this.$message({
                    type: "error",
                    message: '公告内容为空！'
                })
                return
            }
            
            const data = {
                id: this.id,
                title: this.title,
                content: this.content,
                status: "待发布"
            }
            saveNotice(data).then(res => {
                if (res.code === 200) {
                    this.$message({
                        type: "success",
                        message: "公告【" + this.title + "】添加成功"
                    })
                    this.load()
                } else {
                    this.$message({
                        type: "error",
                        message: res.msg
                    })
                }
            })
        },
        
        handleDelete(user) { // 删除
        
        },
        handleDetail(row) {
            const form = JSON.parse(JSON.stringify(row))
            this.id = form.id
            this.content = form.content
            this.title = form.title
            this.dialogFormVisible = true
        },
        handleAvatarSuccess(res) { // 文件上传
            this.form.avatar = res.data
            this.$message.success("上传成功")
            // this.update()
        },
        // -------------------------------------上传头像前的校验----------------------------------
        beforeAvatarUpload(file) {
            const isPNG = file.type === 'image/png'
            const isLt2M = file.size / 1024 / 1024 < 2
            if (!isPNG) {
                this.$message.error('上传头像图片只能是 PNG 格式!')
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!')
            }
            return isPNG && isLt2M
        },
        
        // 时间格式化
        formatDate(row, column) {
            // 获取单元格数据
            let data = row[column.property]
            if (data == null) {
                return ''
            }
            return dayjs(data).format("YYYY-MM-DD HH:mm:ss");
        },
        
        onEditorBlur(quill) {
            console.log("editor blur!", quill);
        },
        onEditorFocus(quill) {
            console.log("editor focus!", quill);
        },
        onEditorReady(quill) {
            console.log("editor ready!", quill);
        },
        onEditorChange({quill, html, text}) {
            console.log("editor change!", quill, html, text);
            this.content = html;
        },
    },
    computed: {
        editor() {
            return this.$refs.myQuillEditor.quill;
        },
    },
}
</script>

<style>
.align-footer {
    text-align: center;
}

.avatar-uploader {
    width: 80px;
    height: 80px;
    border: 1px #b6b9c1 solid;
}

.notice-title {
    display: flex;
    margin-bottom: 5px;
}

/*箭头*/
.el-tooltip__popper[x-placement^="bottom"] .popper__arrow {
    border-bottom-color: #189340 !important;
}

/*箭头*/
.el-tooltip__popper[x-placement^="bottom"] .popper__arrow:after {
    border-bottom-color: #0d3058 !important;
}

/*内容*/
.tip-class {
    background: #2c8ba1 !important;
    box-shadow: 1px 1px 10px 3px #4747c2;
    max-width: 20% !important;
    line-height: 22px;
}

</style>

<style lang="less">

</style>

